package com.easytouch.core.utils;

import android.content.Context;
import android.telephony.TelephonyManager;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * SIM卡工具类，此类需要添加权限android.permission.READ_PHONE_STATE
 * Created by gulin on 2017/10/12.
 */

public class SimTools {
    /**
     * 获得SIM卡号
     * @param context 上下文
     * @return SIM卡号
     */
    public static String getSimNumber(Context context) {
        String simNumber;
        try {
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            simNumber = tManager.getLine1Number() == null ? "" : tManager.getLine1Number().toString();
        } catch (Exception e) {
            //mLogger.i("get sim number occur exception. " + e.getCause());
            simNumber = "";
        }
        return simNumber;
    }

    /**
     * 获取ICCID
     * @param context 上下文
     * @return ICCID号
     */
    public static String getICCID(Context context) {
        String iccid = "";
        try {
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            iccid = tManager.getSimSerialNumber();
            // mLogger.i("001");
        } catch (Exception e) {
            //mLogger.i("get iccid occur exception. " + e.getCause());
            iccid = "";
        }
        //mLogger.i("ICCID = " + iccid);
        return iccid;
    }

    /**
     * 获取设备IP
     * @param context 上下文
     * @return IP地址
     */
    public static String getIPAddress(Context context) {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        ip = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "";
            //mLogger.i("get ip occur SocketException. " + ex.getMessage() + ", " + ex.getCause());
        }
        return ip;
    }
}
